package com.msconfig.mvp.view.fragment;

import android.Manifest;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.geo.msconfig.R;
import com.msconfig.MyApplication;
import com.msconfig.bean.ConfigInfoBean;
import com.msconfig.device.CommandSendManage;
import com.msconfig.device.DeviceManage;
import com.msconfig.device.GetSendCommandList;
import com.msconfig.device.TagSendCommand;
import com.msconfig.event.IsSaveConfigFileGetAllEvent;
import com.msconfig.event.SaveDataToFileSuccessEvent;
import com.msconfig.io.RtkResponseDataListener;
import com.msconfig.mvp.view.activity.MainActivity;
import com.msconfig.utils.DataCacheUtils;
import com.msconfig.utils.GeneralUtil;
import com.msconfig.utils.WriteToFileUtils;
import com.msconfig.widget.RoundRectProgressView;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import static android.view.View.VISIBLE;


public class SaveConfigFragment extends DialogFragment implements View.OnClickListener {
    private RelativeLayout rlLoading;
    private ImageView ivLoading;
    private Animation saveAnim;
    public static final String CONFIGFILE = "configfile4";
    private Context context;
    private String fileName;//配置文件名
    private TextView tvName;
    private TextView tvCancel;
    private TextView tvDetermine;
    private EditText etData;
    public SimpleDateFormat simpleDateFormat;
    private ArrayList<ConfigInfoBean> configInfoBeans;
    protected static final int MSG_SAVE_SUCC =1;
    protected static final int MSG_SAVE_DEFAIL =2;
    private MyHandler myHandler;
    private boolean isSaveOk;//是否保存成功
    public static final int PERMISSIONS_REQUEST_CODE_WRITE_EXTERNAL_STORAGE=5;//写入权限请求吗
    private StringBuilder stringBuilder;



    private static class MyHandler extends Handler {
        WeakReference<SaveConfigFragment> weakReference;

        private MyHandler(SaveConfigFragment fragment) {
            weakReference = new WeakReference<SaveConfigFragment>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            SaveConfigFragment fragment = weakReference.get();
            if (fragment != null) {
                switch (msg.what) {
                    case MSG_SAVE_SUCC:
                        Toast.makeText(fragment.context,"保存成功！",Toast.LENGTH_SHORT).show();
                        break;
                    case MSG_SAVE_DEFAIL:
                        if(!fragment.isSaveOk){//超过5s还是没有获取到GTEALL,OK则表示保存失败
                            //不需要接收数据了
                            DeviceManage.getInstance().RegRtkRespondDataListener(null);
                            //防止已经写入一部分文件，删除掉
                            WriteToFileUtils.deleteFile(fragment.fileName+".txt");
                            fragment.stopAnim();
                            Toast.makeText(fragment.context,"保存失败，请检查通讯是否正常！",Toast.LENGTH_SHORT).show();
                        }
                        break;
                }
            }
        }
    }

    public static SaveConfigFragment newInstance() {
        Bundle bundle=new Bundle();
        SaveConfigFragment fragment = new SaveConfigFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        this.context=context;
        super.onAttach(context);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.layout_fragment_save_config_dialog, container, false);
        rlLoading=view.findViewById(R.id.rl_loading);
        ivLoading = view.findViewById(R.id.iv_loading);
        tvCancel=view.findViewById(R.id.tv_cancel);
        tvCancel.setOnClickListener(this);
        tvDetermine=view.findViewById(R.id.tv_determine);
        tvDetermine.setOnClickListener(this);
        tvName=view.findViewById(R.id.tv_name);
        etData=view.findViewById(R.id.et_input);

        simpleDateFormat=new SimpleDateFormat("yyyy/MM/dd", Locale.CHINA);
        configInfoBeans =new ArrayList<>();
        ArrayList<ConfigInfoBean> beans=DataCacheUtils.loadListCache(context, CONFIGFILE);
        configInfoBeans.addAll(beans);

        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        myHandler =new MyHandler(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_cancel:
                dismiss();
                break;
            case R.id.tv_determine:
                onClickDetermine();
                break;
        }
    }

    private void onClickDetermine() {
        //1.注册rtk回调数据
        //2.发送GETALL获取最新数据
        //3.写入文件
        fileName=etData.getText().toString().trim();
        if(fileName.equals("")){
            Toast.makeText(context,"请输入文件名称！",Toast.LENGTH_SHORT).show();
            return;
        }
        if(!DeviceManage.getInstance().isConnected()){
            Toast.makeText(context,R.string.toast_none_connect, Toast.LENGTH_SHORT).show();
            return;
        }

        //判断文件是不是已经存在
        if(WriteToFileUtils.isExistFile(fileName)){
            Toast.makeText(context,R.string.toast_exist_file, Toast.LENGTH_SHORT).show();
            return;
        }

        //判断是否具有写文件的权限
        if(requestPermission()){
            startSaveConfig();
        }

    }

    private void startSaveConfig() {
        stringBuilder=new StringBuilder();
        isSaveOk=false;
        startAnim();
        myHandler.sendEmptyMessageDelayed(MSG_SAVE_DEFAIL,8000);
        RtkResponseDataListener rtkResponseDataListener=new RtkResponseDataListener() {
            @Override
            //@GNSS,GET,GPS.COORDCVT.ENABLED,OK,1
            public void OnRtkResponseCallBack(String strGnssLine) {
                //表示保存成功
                if(strGnssLine.equals("@GNSS,GETALL,OK")){
                    //stringBuilder拼接后一起写进文件
                    //结束标志
                    stringBuilder.append("@GNSS,GETALL,OK"+"\r\n");
                    WriteToFileUtils.writeMessageToFile(stringBuilder.toString(), fileName);
                    saveConfigSucc();
                    return;
                }
                if (strGnssLine.startsWith(MyApplication.getGlobalContext().getString(R.string.gnss_get_start_with))) {
                    //每一行命令进行拼接
                    stringBuilder.append(strGnssLine+"\r\n");
                }
            }
        };
        //注册Rtk回复数据监听
        DeviceManage.getInstance().RegRtkRespondDataListener(rtkResponseDataListener);

        //发送GETALL命令获取最新数据
        ArrayList<TagSendCommand> sendCommandList = GetSendCommandList.getGetAllCommandList();
        //设置发送命令额集合
        CommandSendManage.getInstance().setSendCommandList(sendCommandList);
        //开始发送命令
        CommandSendManage.getInstance().startSendCommand();
    }

    //返回GETALL表示保存数据成功
    private void saveConfigSucc() {
        isSaveOk=true;
        //一轮配置保存成功
        //只需要这里接收数据，注销回调，防止其他地方获取时这里接收
        DeviceManage.getInstance().RegRtkRespondDataListener(null);
        //保存文件名称和时间
        //保存额是所有的数据
        //在应用配置里面使用
        ConfigInfoBean configInfoBean=new ConfigInfoBean();
        configInfoBean.setFileName(fileName+".txt");
        configInfoBean.setTime(simpleDateFormat.format(new Date()));
        configInfoBeans.add(configInfoBean);
        DataCacheUtils.saveListCache(context, configInfoBeans, CONFIGFILE);
        myHandler.sendEmptyMessage(MSG_SAVE_SUCC);
        dismiss();
        stopAnim();
    }

    //开始动画
    public void startAnim(){
        saveAnim = AnimationUtils.loadAnimation(context, R.anim.anim_round_rotate);
        LinearInterpolator interpolator = new LinearInterpolator();  //设置匀速旋转，在xml文件中设置会出现卡顿
        saveAnim.setInterpolator(interpolator);
        if (saveAnim != null) {
            tvName.setVisibility(View.GONE);
            etData.setVisibility(View.GONE);
            tvCancel.setVisibility(View.GONE);
            tvDetermine.setVisibility(View.GONE);

            rlLoading.setVisibility(VISIBLE);
            ivLoading.startAnimation(saveAnim);  //开始动画
        }
    }

    //停止动画
    private void stopAnim() {
        if (saveAnim != null) {
            saveAnim=null;
            rlLoading.setVisibility(View.GONE);
            ivLoading.clearAnimation();

            tvName.setVisibility(View.VISIBLE);
            etData.setVisibility(View.VISIBLE);
            tvCancel.setVisibility(View.VISIBLE);
            tvDetermine.setVisibility(View.VISIBLE);
        }
    }

    public boolean requestPermission(){
        //6.0以上并且没有授予写权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context.checkSelfPermission(
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            //写入权限
            this.requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                    PERMISSIONS_REQUEST_CODE_WRITE_EXTERNAL_STORAGE);
            return false;
        }else {//不需要申请
            return true;
        }
    }


    //写入权限回调
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case PERMISSIONS_REQUEST_CODE_WRITE_EXTERNAL_STORAGE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED ) {
                    // Permission Granted 授予权限
                    //处理授权之后逻辑
                    startSaveConfig();

                }else{
                    Toast.makeText(context,"请允许APP获取存储权限，否则无法保存配置！",Toast.LENGTH_SHORT).show();
                }
                break;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }


}
